<template>
  <fui-nav-bar
    isOccupy
    isFixed
    background="#0052D9"
    title="选择部门"
    color="#fff"
    @leftClick="leftClick"
  >
    <fui-icon color="#fff" name="arrowleft"></fui-icon>
  </fui-nav-bar>

  <view class="viewport">
    <view class="warp">
      <!-- 搜索框 -->
      <view class="search-box">
        <u--input
          v-model="searchValue"
          placeholder="请输入部门名称搜索"
          prefixIcon="search"
          prefixIconStyle="font-size: 32rpx;color: #909399"
          :border="false"
          @change="handleSearch"
        ></u--input>
      </view>

      <!-- 已选择的部门路径 -->
      <scroll-view
        class="selected-path"
        scroll-x
        v-if="selectedPath.length > 0"
      >
        <view class="path-content">
          <view
            v-for="(item, index) in selectedPath"
            :key="item.id"
            class="path-item"
            :class="{ active: index === selectedPath.length - 1 }"
            @click="selectLevel(index)"
          >
            {{ item.deptName }}
            <text v-if="index < selectedPath.length - 1" class="separator"
              >/</text
            >
          </view>
        </view>
      </scroll-view>

      <!-- 当前级别的部门列表 -->
      <scroll-view
        class="department-list"
        scroll-y
        :refresher-enabled="true"
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
        @scrolltolower="loadMore"
      >
        <view
          v-for="item in currentLevelDepts"
          :key="item.id"
          class="dept-item"
          :class="{ 'has-children': item.children && item.children.length }"
          @click="selectDepartment(item)"
        >
          <view class="dept-content">
            <view class="dept-left">
              <view class="dept-name">{{ item.deptName }}</view>
              <view
                class="dept-full-name"
                v-if="item.fullName !== item.deptName"
              >
                {{ item.fullName }}
              </view>
            </view>
            <view class="dept-right">
              <view class="dept-category" v-if="item.deptCategoryName">
                {{ item.deptCategoryName }}
              </view>
              <view
                class="dept-arrow"
                v-if="item.children && item.children.length"
              >
                <fui-icon name="arrowright" :size="32" color="#666"></fui-icon>
              </view>
            </view>
          </view>
          <view class="dept-extra" v-if="showExtra">
            <view class="extra-item" v-if="item.sort">
              <text class="label">排序：</text>
              <text class="value">{{ item.sort }}</text>
            </view>
            <view class="extra-item" v-if="item.remark">
              <text class="label">备注：</text>
              <text class="value">{{ item.remark }}</text>
            </view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view class="loading-state" v-if="isLoading">
          <fui-loading></fui-loading>
          <text>加载中...</text>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="currentLevelDepts.length === 0">
          <text>暂无部门数据</text>
        </view>
      </scroll-view>
    </view>
  </view>

  <!-- 底部按钮组 -->
  <view class="bottom-button">
    <view class="button-group">
      <button
        class="confirm-btn"
        :class="{ disabled: !canConfirm }"
        @click="confirmSelection"
      >
        确定
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { getDepartmentList } from "@/pages/api/subpkg_institution/repairworkorder.js";

// 搜索关键词
const searchValue = ref("");

// 部门列表数据
const departmentList = ref([]);

// 选中的部门路径
const selectedPath = ref([]);

// 当前选中的部门
const selectedDepartment = ref(null);

// 是否显示额外信息
const showExtra = ref(false);

// 加载状态
const isLoading = ref(false);
const isRefreshing = ref(false);

// 计算当前层级的部门列表
const currentLevelDepts = computed(() => {
  if (selectedPath.value.length === 0) {
    return departmentList.value;
  }

  const lastSelected = selectedPath.value[selectedPath.value.length - 1];
  return lastSelected.children || [];
});

// 是否可以确认选择
const canConfirm = computed(() => {
  return selectedPath.value.length > 0;
});

// 返回上一页
const leftClick = () => {
  uni.navigateBack();
};

// 切换显示额外信息
const toggleExtra = () => {
  showExtra.value = !showExtra.value;
};

// 搜索处理
const handleSearch = () => {
  if (!searchValue.value) {
    loadDepartmentList();
    return;
  }

  // 递归搜索部门
  const searchInDepartments = (departments, keyword) => {
    const results = [];
    departments.forEach((dept) => {
      if (
        dept.deptName.toLowerCase().includes(keyword.toLowerCase()) ||
        dept.fullName.toLowerCase().includes(keyword.toLowerCase())
      ) {
        results.push(dept);
      } else if (dept.children && dept.children.length) {
        const childResults = searchInDepartments(dept.children, keyword);
        if (childResults.length) {
          results.push({
            ...dept,
            children: childResults,
          });
        }
      }
    });
    return results;
  };

  const originalList = departmentList.value;
  const filteredList = searchInDepartments(originalList, searchValue.value);
  departmentList.value = filteredList;
};

// 选择部门
const selectDepartment = (department) => {
  selectedDepartment.value = department;
  selectedPath.value.push(department);
};

// 选择指定层级
const selectLevel = (index) => {
  selectedPath.value = selectedPath.value.slice(0, index + 1);
};

// 确认选择
const confirmSelection = () => {
  if (!selectedDepartment.value) {
    uni.showToast({
      title: "请选择部门",
      icon: "none",
    });
    return;
  }

  // 构建完整的部门路径名称
  const fullPath = selectedPath.value.map((item) => item.deptName).join("/");

  // 触发选择事件
  uni.$emit("departmentSelected", {
    departmentId: selectedDepartment.value.id,
    departmentName: selectedDepartment.value.deptName,
    fullName: selectedDepartment.value.fullName || fullPath,
    deptCategory: selectedDepartment.value.deptCategory,
    deptCategoryName: selectedDepartment.value.deptCategoryName,
    ancestors: selectedDepartment.value.ancestors,
    parentId: selectedDepartment.value.parentId,
    sort: selectedDepartment.value.sort,
    remark: selectedDepartment.value.remark,
  });

  // 返回上一页
  uni.navigateBack();
};

// 下拉刷新
const onRefresh = async () => {
  isRefreshing.value = true;
  await loadDepartmentList();
  isRefreshing.value = false;
};

// 加载更多
const loadMore = () => {
  // 这里可以实现分页加载
  console.log("加载更多数据");
};

// 获取部门列表数据
const loadDepartmentList = async () => {
  try {
    isLoading.value = true;
    const res = await getDepartmentList();
    if (res.code === 200 && res.success) {
      departmentList.value = res.data;
    } else {
      uni.showToast({
        title: res.msg || "获取部门列表失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("获取部门列表失败:", error);
    uni.showToast({
      title: "获取部门列表失败",
      icon: "none",
    });
  } finally {
    isLoading.value = false;
  }
};

// 页面加载时获取部门列表
loadDepartmentList();
</script>

<style lang="scss" scoped>
page {
  display: flex;
  height: 100%;
  overflow: hidden;
  flex-direction: column;
  background-color: #f5f5f5;
}

.viewport {
  flex: 1;
  display: flex;
  overflow: hidden;
  flex-direction: column;
}

.warp {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .search-box {
    padding: 20rpx 30rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;

    :deep(.u-input) {
      height: 80rpx;
      background-color: #f5f5f5;
      border-radius: 40rpx;
      padding: 0 30rpx;
    }
  }

  .selected-path {
    white-space: nowrap;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;

    .path-content {
      display: inline-flex;
      padding: 20rpx 30rpx;

      .path-item {
        font-size: 28rpx;
        color: #666;
        display: flex;
        align-items: center;

        &.active {
          color: #0052d9;
          font-weight: 500;
        }

        .separator {
          margin: 0 10rpx;
          color: #999;
        }
      }
    }
  }

  .department-list {
    flex: 1;
    background-color: #fff;

    .dept-item {
      margin: 0 30rpx;
      padding: 24rpx 0;
      border-bottom: 1rpx solid #eee;

      &:last-child {
        border-bottom: none;
      }

      &.has-children {
        .dept-content {
          padding-right: 40rpx;
        }
      }

      .dept-content {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;

        .dept-left {
          flex: 1;
          margin-right: 20rpx;

          .dept-name {
            font-size: 30rpx;
            color: #333;
            font-weight: 500;
          }

          .dept-full-name {
            font-size: 24rpx;
            color: #999;
            margin-top: 8rpx;
          }
        }

        .dept-right {
          display: flex;
          align-items: center;

          .dept-category {
            font-size: 24rpx;
            color: #666;
            background-color: #f5f5f5;
            padding: 4rpx 12rpx;
            border-radius: 4rpx;
            margin-right: 16rpx;
          }
        }
      }

      .dept-extra {
        margin-top: 16rpx;
        padding-top: 16rpx;
        border-top: 1rpx dashed #eee;

        .extra-item {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 8rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .label {
            color: #999;
          }
        }
      }
    }

    .loading-state {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 30rpx;
      color: #999;
      font-size: 28rpx;

      text {
        margin-left: 12rpx;
      }
    }

    .empty-state {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 60rpx 30rpx;
      color: #999;
      font-size: 28rpx;
    }
  }
}

.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .button-group {
    display: flex;
    gap: 20rpx;

    .extra-btn {
      flex: 1;
      height: 90rpx;
      line-height: 90rpx;
      text-align: center;
      font-size: 32rpx;
      color: #666;
      background-color: #f5f5f5;
      border-radius: 45rpx;

      &.active {
        color: #0052d9;
        background-color: #eef5ff;
      }
    }

    .confirm-btn {
      flex: 2;
      background-color: #0052d9;
      color: #fff;
      border-radius: 45rpx;
      font-size: 32rpx;
      height: 90rpx;
      line-height: 90rpx;

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
</style>
